package com.smartcar.auth.controller;

import com.smartcar.auth.service.AuthService;
import com.smartcar.common.domain.User;
import com.smartcar.common.domain.request.LoginRequest;
import com.smartcar.common.domain.response.TokenResponse;
import com.smartcar.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Log4j2
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 登录
     */
    @PostMapping("login")
    public Result<TokenResponse> login(@RequestBody LoginRequest loginRequest) {
        log.info("方法名称：登录，参数：{}", loginRequest.toString());
        Result<TokenResponse> result = authService.login(loginRequest);
        log.info("方法名称：登录，参数：{}，结果：{}", loginRequest.toString(), result.toString());
        return result;
    }

    /**
     * 获取用户信息
     */
    @GetMapping("user/info")
    public Result<User> userInfo() {
        log.info("方法名称：获取用户信息");
        User user = authService.userInfo();
        Result<User> result = Result.success(user);
        log.info("方法名称：获取用户信息，结果：{}", result.toString());
        return result;
    }

    /**
     * 登出方法
     */
    @DeleteMapping("logout")
    public Result logout(HttpServletRequest request) {
        Result result = authService.logout();
        log.info("方法名称：登出，执行状态：{}", result.getCode());
        return result;
    }

    /**
     * 注册
     */
    @PostMapping("registered")
    public Result registered(@RequestBody User user) {
        log.info("方法名称：用户注册，参数：{}", user.toString());
        Result result = authService.registered(user);
        log.info("方法名称：用户注册，参数：{}，结果：{}", user.toString(), result.getCode());
        return result;
    }
    /**
     * 获取验证码
     */
    @GetMapping("/getCode/{phone}")
    public Result getCode(@PathVariable String phone){
        log.info("方法名称：获取验证码，参数：{}",phone);
        RRateLimiter rateLimiter = redissonClient.getRateLimiter("rateLimit" + phone);
        //10秒产生3个令牌
        rateLimiter.trySetRate(RateType.OVERALL,3,10, RateIntervalUnit.SECONDS);
        //每次请求获取一个令牌
        boolean flag = rateLimiter.tryAcquire(1);
        if (!flag){
            return Result.error("请求频繁");
        }
        Result code = authService.getCode(phone);
        log.info("方法名称：获取验证码，参数：{}，结果：{}",phone,code.getData());
        return Result.success(code);
    }
}
